package adapletplugin.commands;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

import objects.MappingFile;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

import adapletplugin.Activator;
import adapletplugin.editors.MapFileEditor;
import adapletplugin.editors.input.MapFileEditorInput;

public class Load extends AbstractHandler
{

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException
	{
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();

		FileDialog dialog = new FileDialog(shell, SWT.OPEN);

		dialog.setFilterExtensions(new String[] { "*.ser" });

		dialog.open();

		String inFileName = dialog.getFileName();
		String inFilePath = dialog.getFilterPath();

		if (inFileName == null || inFilePath == null)
		{
			return null;
		}

		FileInputStream inFStream = null;
		ObjectInputStream inOStream = null;

		try
		{
			inFStream = new FileInputStream(new File(inFilePath, inFileName));
			inOStream = new ObjectInputStream(inFStream);

			MappingFile mapFile = (MappingFile) inOStream.readObject();

			inOStream.close();
			inOStream = null;

			inFStream.close();
			inFStream = null;

			Activator.getDefault().setCurrentProject(mapFile);

			IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

			page.openEditor(new MapFileEditorInput(mapFile), MapFileEditor.ID);

		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (PartInitException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

}
